var menu_show = false

var mouseX = 0;
var mouseY = 0;

var menu_callback = function () { }

function create_menu(list, x, y) { // 创建右键菜单
    if (menu_show) {
        destory_menu() // 避免菜单重叠
    }
    var height = list.length * 34 + 2
    // 计算座标
    if (y + height > window.innerHeight) {
        var pos_y_type = "bottom"
        var pos_y = 0
        var max_y = window.innerHeight
    } else {
        var pos_y_type = "top"
        var pos_y = y
        var max_y = window.innerHeight - y
    }
    if (x + 180 > window.innerWidth) {
        var pos_x_type = "right"
        var pos_x = window.innerWidth - x
    } else {
        var pos_x_type = "left"
        var pos_x = x
    }
    // 构建菜单html
    var template = `<div id="click_menu_cover" oncontextmenu="event.preventDefault();destory_menu()"></div>`
    template += `<div id="click_menu" style="${pos_x_type}: ${pos_x}px; ${pos_y_type}: ${pos_y}px; max-height: ${max_y}px; overflow-y: auto; height:${height}px;" oncontextmenu="event.preventDefault();destory_menu()">`
    for (var i = 0; i < list.length; i++) {
        template += `<button class="click_menu_item" onclick="click_menu_item(${i})" oncontextmenu="event.preventDefault();destory_menu()">${list[i]}</button>`
    }
    template += `</div>`
    document.getElementsByTagName("body")[0].insertAdjacentHTML("afterbegin", template)
    setTimeout(() => { // 设置事件
        document.getElementById("click_menu_cover").addEventListener("click", function () {
            destory_menu()
        })
    }, 0)
    menu_show = true
}

function destory_menu() { // 销毁
    if (!menu_show) {
        return
    }
    menu_callback = function () { }
    document.getElementById("click_menu_cover").remove()
    document.getElementById("click_menu").remove()
    menu_show = false
}

function click_menu_item(index) { // 点击事件
    menu_callback(index)
    destory_menu()
}

document.addEventListener('mousemove', function (event) { // 记录鼠标位置
    mouseX = event.clientX;
    mouseY = event.clientY;
});

function create_menu_on_mouse(list) {
    create_menu(list, mouseX, mouseY)
}

CHECK_DESKTOP_MENU = 1